/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.letmeshare.stockkeeper.stock.module;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.letmeshare.stockkeeper.stock.entities.Category;

/**
 *
 * @author ibisuser1
 */
public class CategoryModule {
    
    private EntityManager em;
    
    public static CategoryModule getInstance(EntityManager em) {
        if (em == null) {
            return null;
        }
        return new CategoryModule(em);
    }
    
    private CategoryModule (EntityManager em) {
        this.em = em;
    }
    
    public void createCategory (Category category) {
        if (category == null) {
            throw new IllegalArgumentException("Category required");
        }
        category.validate();
        em.persist(category);
    }
    
    public void updateCategory (Category category) {
        if (category == null) {
            throw new IllegalArgumentException("Category required");
        }
        Category oldCategory = getCategory(category.getId());
        oldCategory.setName(category.getName());
        category.validate();
        em.merge(category);
    }
    
    public void deleteCategory (Category category) {
        if (category == null) {
            throw new IllegalArgumentException("Category required");
        }//TODO make items of this category uncategorised
        em.merge(category);
    }
    
    public Category getCategory (String id) {
        if (id == null) {
            throw new IllegalArgumentException("Id required");
        }
        return em.find(Category.class, id);
    }
    
    public Category getCategoryByName (String name) {
        Query query = em.createQuery("SELECT category FROM Category category WHERE category.name = :name");
        query.setParameter("name", name);
        List<Category> categories = query.getResultList();
        return categories.isEmpty() ? null : categories.get(0);
    }
    
    public Category getCategoryByCode (String code) {
        Query query = em.createQuery("SELECT category FROM Category category WHERE category.code = :code");
        query.setParameter("code", code);
        List<Category> categories = query.getResultList();
        return categories.isEmpty() ? null : categories.get(0);
    }
}
